//
//  XPersonalDataViewController.m
//  ReceiveVouchers
//
//  Created by Veer on 2017/11/14.
//  Copyright © 2017年 ReceiveVouchers. All rights reserved.
//

#import "XPersonalDataViewController.h"

#import "XPersonDataHeaderCell.h"
#import "XNicknameAlertView.h"
#import "XSexAlertView.h"
#import "XBirthdayAlertView.h"

#import "XMeCell.h"
#import "NSString+Tools.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import "UIImage+VR.h"
#import "KAUserinfoModel.h"


@interface XPersonalDataViewController () <UITableViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, weak) XNicknameAlertView *alertView;

@end

@implementation XPersonalDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人信息";
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setupSection0];
}


- (void)setupSection0
{
    //    __block typeof(self) weakself = self;
    WeakSelf(weakSelf)
    NSString *headerName = self.userinfoModel.image.length > 0 ? self.userinfoModel.image : nil;
    XSettingItemModel *item0 = [XSettingItemModel itemWithIcon:headerName name:@"头像"];
//    item0.isHaveArrow = YES;
    //    item0.destVcClass = [XModifyPhoneNumberViewController class];
    item0.executeOperation = ^(NSIndexPath *indexPath) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择", nil];
            sheet.tag = 100;
            [sheet showInView:self.view];
        });
    };
    
    NSString *nickName = self.userinfoModel.name.length > 0 ? self.userinfoModel.name : @"";
    XSettingItemModel *item1 = [XSettingItemModel itemWithIcon:nil name:@"昵称" detail:nickName];
    item1.isHaveArrow = YES;
    item1.executeOperation = ^(NSIndexPath *indexPath) {
        
        XNicknameAlertView *alertView = [[XNicknameAlertView alloc] init];
//        alertView.titleLbl.text = @"请输入您的昵称";
//        alertView.textView.placeholder = @"";
        alertView.text = weakSelf.userinfoModel.name;
        alertView.SaveBlock = ^(NSString *text) {
            
            weakSelf.userinfoModel.name = text;
            [[KADataBase sharedDataBase] updateUserinfo:weakSelf.userinfoModel];
            
            XSettingSectionModel *sectionModel = weakSelf.sectionArray[0];
            XSettingItemModel *itemModel = sectionModel.itemArray[1];
            itemModel.detail = text;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [self.alertView dissmiss];
        };
    
        [alertView show];
        weakSelf.alertView = alertView;
    };
    
    NSString *gender = self.userinfoModel.gender == 2 ? @"女" : @"男";
    if (self.userinfoModel.gender < 0) {
        gender = nil;
    }
    XSettingItemModel *item2 = [XSettingItemModel itemWithIcon:nil name:@"性别" detail:gender];
    item2.isHaveArrow = YES;
    item2.executeOperation = ^(NSIndexPath *indexPath) {
        
//        XSexAlertView *alertView = [[XSexAlertView alloc] init];
////        alertView.defualtSelectedIndex = weakSelf.userinfoModel.xUser.gender == 2 ? 1 : 0;
//        alertView.SelectedBlock = ^(NSInteger index) {
//
////            [weakSelf modifyPersonDataWithHeader:nil nickName:nil gender:index + 1];
//        };
//        [alertView show];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男", @"女", nil];
            sheet.tag = 101;
            [sheet showInView:self.view];
        });
    };
    
    // 暂时去掉
    NSString *phone = self.userinfoModel.phone.length > 0 ? self.userinfoModel.phone : nil;
    XSettingItemModel *item3 = [XSettingItemModel itemWithIcon:nil name:@"手机号" detail:phone];
    item3.isHaveArrow = YES;
    item3.executeOperation = ^(NSIndexPath *indexPath) {
        
        XNicknameAlertView *alertView = [[XNicknameAlertView alloc] init];
        alertView.textView.keyboardType = UIKeyboardTypeNumberPad;
        alertView.titleLbl.text = @"请输入您的手机号";
        alertView.textView.placeholder = @"";
        alertView.text = weakSelf.userinfoModel.phone;
        alertView.SaveBlock = ^(NSString *text) {
            
            weakSelf.userinfoModel.phone = text;
            [[KADataBase sharedDataBase] updateUserinfo:weakSelf.userinfoModel];
            
            XSettingSectionModel *sectionModel = self.sectionArray[0];
            XSettingItemModel *itemModel = sectionModel.itemArray[3];
            itemModel.detail = text;
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
            [weakSelf.tableView reloadData];
            [weakSelf.alertView dissmiss];
        };
        [alertView show];
        weakSelf.alertView = alertView;
    };
    
    
    XSettingItemModel *item4 = [XSettingItemModel itemWithIcon:nil name:@"出生年月" detail:@"123"];
    item4.isHaveArrow = YES;
    item4.executeOperation = ^(NSIndexPath *indexPath) {
        
        XBirthdayAlertView *alertView = [[XBirthdayAlertView alloc] init];
        alertView.defaultDateStr = @"1991-01-01";
        alertView.SaveBlock = ^(NSString *dateStr) {
            
            XSettingSectionModel *sectionModel = weakSelf.sectionArray[indexPath.section];
            XSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
            itemModel.detail = dateStr;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        [alertView show];
    };
    
    
    XSettingSectionModel *section0 = [[XSettingSectionModel alloc]init];
    section0.itemArray = [@[item0, item1, item2, item3] mutableCopy];
    
    [self.sectionArray addObject:section0];
}


- (void)takePhotoFromCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:NAVColor] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)takePhotoFromPhotoLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
//        NSDictionary *dic = [XCommonMethod X_ReadJsonFileWithNFileName:[TXSakuraManager getSakuraCurrentName]];
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:NAVColor] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.navigationBar.barTintColor = [UIColor colorWithRed:20.f/255.0 green:24.0/255.0 blue:38.0/255.0 alpha:1];
        [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
    }
}


#pragma mark - getdata
- (void)saveImageWith:(UIImage *)image
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingString:@"/header.jpeg"];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    
    
    UIImage *newImage = [UIImage compressImage:image toSize:CGSizeMake(100, 100) toMaxFileSize:200 * 1024];
    NSData *newImgData = UIImageJPEGRepresentation(newImage, 1.0);
    
    [newImgData writeToFile:path atomically:YES];
    self.userinfoModel.image = @"header.jpeg";
    [[KADataBase sharedDataBase] updateUserinfo:self.userinfoModel];
    
    XSettingSectionModel *sectionModel = self.sectionArray[0];
    XSettingItemModel *itemModel = sectionModel.itemArray[0];
    itemModel.icon = self.userinfoModel.image;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.alertView dissmiss];
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 54;
    }else{
        return 45;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出数据模型
    XSettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    XSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    if (indexPath.row == 0) {
        
        XPersonDataHeaderCell *cell = [XPersonDataHeaderCell cellWith:tableView];
        cell.model = itemModel;
        return cell;
    }else{

        XMeCell *cell = [XMeCell cellWith:tableView];
        cell.model = itemModel;
        if (indexPath.row < sectionModel.itemArray.count - 1) {
            
            cell.lineType = LineTypeCenter;
        }else{
            
            cell.lineType = LineTypeTopAndBottom;
        }
        
        return cell;
    }
}

#pragma mark actionSheet代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (actionSheet.tag == 100) {
        
        if (0 == buttonIndex) {
            
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if(authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经取消了“领券”访问您的相机权限，若要继续操作请到手机“设置->隐私”设置开启" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
                return;
            }
            
            [self takePhotoFromCamera];
        }else if (1 == buttonIndex){
            
            
            ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
            if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经取消了“领券”访问您的相册权限，若要继续操作请到手机“设置->隐私”设置开启" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
                return;
            }
            
            [self takePhotoFromPhotoLibrary];
        }
    }else if (actionSheet.tag == 101){
        
        if (0 == buttonIndex) {
            
            self.userinfoModel.gender = 1;
            
            XSettingSectionModel *sectionModel = self.sectionArray[0];
            XSettingItemModel *itemModel = sectionModel.itemArray[2];
            itemModel.detail = @"男";
        }else if (1 == buttonIndex){
            
            self.userinfoModel.gender = 2;
            
            XSettingSectionModel *sectionModel = self.sectionArray[0];
            XSettingItemModel *itemModel = sectionModel.itemArray[2];
            itemModel.detail = @"女";
        }
        
        [[KADataBase sharedDataBase] updateUserinfo:self.userinfoModel];
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
}

#pragma mark - UIImagePickerController Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *resultImage = info[UIImagePickerControllerEditedImage];
    [self saveImageWith:resultImage];
    
//    [self uploadImgToUpYunWith:resultImage];
//    [self uploadImgWith:resultImage];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}


@end
